package drds.common.db.xml_mapping.parameter_and_result_value_type;

import java.io.StringReader;
import java.sql.Clob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class ClobTypeHandler extends BaseTypeHandler<String> {

  @Override
  public void setNonNullParameter(PreparedStatement preparedStatement, int index, String parameter, JdbcType jdbcType)
    throws SQLException {
    StringReader stringReader = new StringReader(parameter);
    preparedStatement.setCharacterStream(index, stringReader, parameter.length());
  }

  @Override
  public String getNullableResult(ResultSet resultSet, String columnName)
    throws SQLException {
    Clob clob = resultSet.getClob(columnName);
    return toString(clob);
  }

  @Override
  public String getNullableResult(ResultSet resultSet, int columnIndex)
    throws SQLException {
    Clob clob = resultSet.getClob(columnIndex);
    return toString(clob);
  }

  private String toString(Clob clob) throws SQLException {
    return clob == null ? null : clob.getSubString(1, (int) clob.length());
  }

}
